//
//  MCMainNavigationController.m
//  TLYL
//
//  Created by miaocai on 2017/6/1.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCMainNavigationController.h"
#import "MCPaySelectedLotteryTableViewController.h"
#import "MCMSPopView.h"
#import "MCMoneyPopView.h"
#import "MCPickNumberViewController.h"
#import "MCPaySelectedLotteryModel.h"
#import "MCBaseSelectedView.h"
#import "MCRechargeViewController.h"
#import "MCMineAddBankCardViewController.h"
#import "MCModifyPayPasswordViewController.h"
#import "MCWithdrawRecDeltailViewController.h"
#import "MCMineInfoModel.h"
#import "MCHasPayPwdModel.h"
#import "MCLoginOutModel.h"
#import "MCUserDefinedLotteryCategoriesViewController.h"
#import "MCGetMerchantInfoModel.h"
#import "MCLoginViewController.h"
#import "MCSystemNoticeViewController.h"
#import "MCGameRecordViewController.h"
#import "UIView+MCParentController.h"
#import "MCPopAlertView.h"
#import "MCModifyUserImgVViewController.h"
#import "MCPersonInformationViewController.h"
#import "MCNewZhuanZhangViewController.h"
#import "MCGetSecurityStateModel.h"
#import "MCMSecureSettingViewController.h"
#import "MCTeamMgTabbarController.h"
#import "MCNewActivityViewController.h"
#import "MCHelpCenterViewController.h"
#import "MCKefuViewController.h"
#import "MCGetRandomSecurityModel.h"
#import "MCRetrievePasswordModel.h"
#import "MCPullMenuTool.h"
@interface MCMainNavigationController ()
typedef void(^MCMainNavigationControllerCompeletion)(BOOL result, NSDictionary *data );
@property (nonatomic,getter=isPushing)BOOL pushing;
@property (nonatomic,weak) UIView *coverView;
@property (nonatomic,weak) UIImageView * screenImgV;
@property (nonatomic,weak) MCBaseSelectedView *selectedView;
@property (nonatomic,assign) BOOL isOpen;
@property (nonatomic,strong)MCLoginOutModel  * loginOutModel;
@property (nonatomic,strong)MCGetSecurityStateModel * getSecurityStateModel;
//获取所有的密保问题
@property(nonatomic, strong)MCGetRandomSecurityModel * getRandomSecurityModel;
//验证密保答案是否正确
@property(nonatomic, strong)MCRetrievePasswordModel  * retrievePasswordModel;
@property(nonatomic, weak)UIAlertAction *sureAction;
@property(nonatomic, weak)UITextField * textField;
@end

@implementation MCMainNavigationController
- (UIView *)coverView{
    if (_coverView == nil) {
        UIView *coverView = [[UIView alloc] initWithFrame:self.view.bounds];
        [[UIApplication sharedApplication].keyWindow addSubview:coverView];
        coverView.backgroundColor = [RGB(0, 0, 0) colorWithAlphaComponent:1];
        MCBaseSelectedView *selectedView =[[MCBaseSelectedView alloc]init];
        [coverView addSubview:selectedView];
        UIImageView * screenImgV=[[UIImageView alloc]init];
        screenImgV.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT);
        screenImgV.userInteractionEnabled=YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverViewClick)];
        [screenImgV addGestureRecognizer:tap];
        _screenImgV=screenImgV;
        [coverView addSubview:_screenImgV];
        selectedView.frame=CGRectMake(0, 0, G_SCREENWIDTH, 300);
    
        selectedView.block = ^(NSInteger type) {
            [self MCBaseSelectedViewActionHandlerWithType:type];
        };
        _selectedView=selectedView;
        _coverView = coverView;
    }
    return _coverView;
}

-(void)MCBaseSelectedViewActionHandlerWithType:(NSInteger)tag{
    UIViewController *vc = nil;
//    NSLog(@"%lu",self.tabBarController.selectedIndex);
    __weak __typeof(self)wself = self;
    if (tag==1001) {//充值
        [self coverViewClick];
        MCMineInfoModel * mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
        if ([mineInfoModel.UserType intValue] ==1) {
            [SVProgressHUD showInfoWithStatus:@"您无充值权限！"];
            return;
        }
        MCRechargeViewController * VC =[[MCRechargeViewController alloc]init];
        [self pushViewController:VC animated:YES];
    }else if(tag==1002){//提款
        [self coverViewClick];
        [self goToWithdrawViewController];
    }else if(tag==1003){//转账
        
        [self coverViewClick];
        
        [self goToZhuanzhangViewController];
        
//        MCHasPayPwdModel *hasPayPwdModel = [MCHasPayPwdModel sharedMCHasPayPwdModel];
//        BOOL hasPassword = [hasPayPwdModel.PayOutPassWord intValue]==1?YES:NO;
//        if(hasPassword){
//        }else{
//            [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
//            [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
//
//            return;
//        }
//
//        MCQiPaizhuanzhangViewController * VC =[[MCQiPaizhuanzhangViewController alloc]init];
//        [self pushViewController:VC animated:YES];
        
    }else if(tag==2000){//购彩大厅
        [self coverViewClick];
        self.tabBarController.selectedIndex = 1;
    }else if(tag==2001){//优惠活动
        [self coverViewClick];
         vc = [[MCNewActivityViewController alloc] init];
        [self pushViewController:vc animated:YES];
    }else if(tag==2002){//会员中心
 
        MCMineInfoModel *mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
        if (mineInfoModel.IsAgent==NO) {
            [SVProgressHUD showInfoWithStatus:@"你不是代理用户,没有权限操作此功能!"];
            return;
        }
        [self coverViewClick];
        
        [self performSelector:@selector(gotoTeamMgTabbarController) withObject:nil afterDelay:0];
     

    }else if(tag==2003){//系统公告
        
        [self coverViewClick];
        NSNumber *n = [[NSUserDefaults standardUserDefaults] objectForKey:@"MCSystemNoticeListCount"];
        if (n.boolValue == YES) {
            MCSystemNoticeViewController * vc=[[MCSystemNoticeViewController alloc]init];
            [self pushViewController:vc animated:YES];
        } else {
            [SVProgressHUD showInfoWithStatus:@"暂无公告"];
             return;
        }
       
    }else if (tag==2004){//开奖公告

        [self coverViewClick];
        self.tabBarController.selectedIndex = 2;
        
    }else if (tag==2005){//游戏记录

        [self coverViewClick];
        if (self.tabBarController.selectedIndex==3) {
            MCGameRecordViewController * vc=[[MCGameRecordViewController alloc]init];
            [self pushViewController:vc animated:YES];
        }else{
            self.tabBarController.selectedIndex = 3;
            [UIView animateWithDuration:0.001 animations:^{
            } completion:^(BOOL finished) {
                [[NSNotificationCenter defaultCenter] postNotificationName:MainNavigationGameRecordClickedNotification object:nil userInfo:nil];
            }];
            
        }
        
        
        
    }else if(tag==2006){//彩票走势
 
        [SVProgressHUD showInfoWithStatus: @"功能完善中..."];
    }else if (tag==2007){//使用帮助
        [self coverViewClick];
        MCHelpCenterViewController * hVc= [[MCHelpCenterViewController alloc]init];
        [self pushViewController:hVc animated:YES];

    }else if (tag==2008){//在线客服
       self.automaticallyAdjustsScrollViewInsets = YES;
        [self coverViewClick];
        MCKefuViewController *vc =  [[MCKefuViewController alloc] init];
        vc.title = @"联系客服";
        [self pushViewController:vc animated:YES];
        
    }else if (tag==2009){//修改头像
        [self coverViewClick];
        MCModifyUserImgVViewController *ivc  = [[MCModifyUserImgVViewController alloc] init];
        ivc.userImgBlock = ^{
            [wself.selectedView refreashImgVIcon];
        };
        [self pushViewController:ivc animated:YES];

    }else if (tag==2010){//修改昵称
        [self coverViewClick];
        MCPersonInformationViewController * VC =[[MCPersonInformationViewController alloc]init];
        [self pushViewController:VC animated:YES];

    }else if (tag==3000){//退出登录
        [self coverViewClick];
        [self performLogOut];
    }
    
    
}
- (void)gotoTeamMgTabbarController{
    MCTeamMgTabbarController *vc  = [[MCTeamMgTabbarController alloc] init];
    [self pushViewController:vc animated:YES];
}
#pragma mark-  /退出登录/
-(void)performLogOut{
    __weak __typeof__ (self) wself = self;
    
    MCCancelPopView * popView=[MCCancelPopView InitPopViewWithTitle:@"确定要退出登录吗？" sureTitle:@"确定" andCancelTitle:@"取消"];
    [popView show];
    popView.block = ^(NSInteger type) {
        if (type==1) {
            [wself requestLoginOut];
        }
    };
    
}

-(void)requestLoginOut{

    

    MCMineInfoModel *mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
    mineInfoModel = nil;
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:MCRefreshMineDataUI];
    MCLoginOutModel  * loginOutModel =[[MCLoginOutModel alloc]init];
    [loginOutModel refreashDataAndShow];
    self.loginOutModel=loginOutModel;
    MCLoginViewController *log = [[MCLoginViewController alloc] init];
    log.presented = NO;
    MCMainNavigationController *nav = [[MCMainNavigationController alloc] initWithRootViewController:log];
    
    [[[UIApplication sharedApplication] keyWindow] setRootViewController:nav];
    loginOutModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        [[NSUserDefaults standardUserDefaults] setObject:@"logout" forKey:@"logout"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cookie_id"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"MCSystemNoticeListCount"];
        [[MCGetMerchantInfoModel sharedMCGetMerchantInfoModel] clearData];
        [MCUserDefinedLotteryCategoriesViewController clearUserDefinedCZ];
        [MCPullMenuTool clearAllSelectedPlayCodeData];
    };
    loginOutModel.callBackSuccessBlock = ^(id manager) {
        [[NSUserDefaults standardUserDefaults] setObject:@"logout" forKey:@"logout"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cookie_id"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"MCSystemNoticeListCount"];
        [[MCGetMerchantInfoModel sharedMCGetMerchantInfoModel] clearData];
        [MCUserDefinedLotteryCategoriesViewController clearUserDefinedCZ];
//        [[[UIApplication sharedApplication] keyWindow] setRootViewController:[[MCLoginViewController alloc] init]];
        [MCPullMenuTool clearAllSelectedPlayCodeData];
    };
}


/*
 * 跳转提现
 */
-(void)goToWithdrawViewController{
    MCMineInfoModel * mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
    MCHasPayPwdModel *hasPayPwdModel = [MCHasPayPwdModel sharedMCHasPayPwdModel];
    if ([mineInfoModel.UserType intValue] ==1) {
        [SVProgressHUD showInfoWithStatus:@"您无提款权限！"];
        return;
    }
    BOOL hasCard = [mineInfoModel.BankCardNumber length]>1?YES:NO;
    BOOL hasPassword = [hasPayPwdModel.PayOutPassWord intValue]==1?YES:NO;
    
    /*
     * 情况一： 无资金密码  无默认银行卡
     */
    if (!hasCard&&!hasPassword) {
        [SVProgressHUD showInfoWithStatus:@"请先完善银行卡！"];
        
        [self performSelector:@selector(delay_GoToMCMineAddBankCardViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];

        //情况二： 有资金密码  无默认银行卡
    }else if (hasPassword&&!hasCard){
        
        //先绑卡-》退回我的
        [SVProgressHUD showInfoWithStatus:@"请先完善银行卡！"];
        
        [self performSelector:@selector(delay_GoToMCMineAddBankCardViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];

        
        //情况三： 无资金密码  有默认银行卡
    }else if (!hasPassword&&hasCard){
        
        //设置资金密码-》退回我的
        //        [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
        
        MCGetSecurityStateModel * getSecurityStateModel = [MCGetSecurityStateModel sharedMCGetSecurityStateModel];
        if (getSecurityStateModel.hadSecurityState.length>0) {
            if ([getSecurityStateModel.hadSecurityState integerValue]==1) {
                //设置资金密码-》退回我的
                [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                
                
            }else{
                //设置密保
                [SVProgressHUD showInfoWithStatus:@"请先设置密保！"];
                
                
                [self performSelector:@selector(delay_GoToMCMSecureSettingViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                
            }
        }else{
            __weak __typeof(self)wself = self;
            [self GetSecurityState:^(BOOL result, NSDictionary *data) {
                if (result) {
                    wself.getSecurityStateModel.hadSecurityState=[NSString stringWithFormat:@"%@",data[@"Result"]];
                    if ([wself.getSecurityStateModel.hadSecurityState integerValue]==1) {
                        //设置资金密码-》退回我的
                        [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                        
                        [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                        
                    }else{
                        [SVProgressHUD showInfoWithStatus:@"加载失败！"];
                    }
                }
            }];
        }
        //情况四： 有资金密码  有默认银行卡
    }else{
        [self coverViewClick];
        MCWithdrawRecDeltailViewController * vc=[[MCWithdrawRecDeltailViewController alloc]init];
        self.navigationBarHidden=NO;
        [self pushViewController:vc animated:YES];
    }
    
}
#pragma mark-跳转转账
-(void)goToZhuanzhangViewController{
    MCHasPayPwdModel *hasPayPwdModel = [MCHasPayPwdModel sharedMCHasPayPwdModel];
    BOOL hasPassword = [hasPayPwdModel.PayOutPassWord intValue]==1?YES:NO;
    if(hasPassword){
        MCNewZhuanZhangViewController * vc  = [[MCNewZhuanZhangViewController alloc] init];
        self.navigationBarHidden=NO;
        [self pushViewController:vc animated:YES];
    }else{
        
        MCGetSecurityStateModel * getSecurityStateModel = [MCGetSecurityStateModel sharedMCGetSecurityStateModel];
        if (getSecurityStateModel.hadSecurityState.length>0) {
            if ([getSecurityStateModel.hadSecurityState integerValue]==1) {
                //设置资金密码-》退回我的
                [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                
                
            }else{
                //设置密保
                [SVProgressHUD showInfoWithStatus:@"请先设置密保！"];
                
                
                [self performSelector:@selector(delay_GoToMCMSecureSettingViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                
            }
        }else{
            __weak __typeof(self)wself = self;
            [self GetSecurityState:^(BOOL result, NSDictionary *data) {
                if (result) {
                    wself.getSecurityStateModel.hadSecurityState=[NSString stringWithFormat:@"%@",data[@"Result"]];
                    if ([wself.getSecurityStateModel.hadSecurityState integerValue]==1) {
                        //设置资金密码-》退回我的
                        [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                        
                        [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                        
                    }else{
                        [SVProgressHUD showInfoWithStatus:@"加载失败！"];
                    }
                }
            }];
        }
    }
}

-(void)GetSecurityState:(MCMainNavigationControllerCompeletion)Compeletion{
    __weak __typeof(self)wself = self;
    MCGetSecurityStateModel * getSecurityStateModel = [MCGetSecurityStateModel sharedMCGetSecurityStateModel];
    _getSecurityStateModel=getSecurityStateModel;
    [getSecurityStateModel refreashDataAndShow];
    getSecurityStateModel.callBackSuccessBlock = ^(id manager) {
        wself.getSecurityStateModel.hadSecurityState=[NSString stringWithFormat:@"%@",manager[@"Result"]];
        Compeletion(YES,manager);
    };
    getSecurityStateModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
        wself.getSecurityStateModel.hadSecurityState=nil;
        Compeletion(NO,nil);
    };
}
 
+(void)load{

  UINavigationBar *bar =[UINavigationBar appearance];
    bar.barTintColor = MC_THEME_COLOR;
    bar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:MC_REALVALUE(16)]};
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
 
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
//    viewController.navigationController.navigationBarHidden=NO;
//    viewController.navigationController.navigationBar.translucent = NO;
    MCMoneyPopView *popView = [MCMoneyPopView alertInstance];
    [popView hideModelWindow];
    MCMSPopView *popView1 = [MCMSPopView alertInstance];
    [popView1 hideModelWindow];
    if (self.childViewControllers.count == 0) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"home-icon-more"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"home-icon-more"] forState:UIControlStateHighlighted];
        button.size = CGSizeMake(50, 44);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, -7, 0, 0);
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(personInfoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        
    } else {
        
    }
    if (self.childViewControllers.count > 0) { // 如果push进来的不是第一个控制器
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateHighlighted];
        [button setTitle:@"返回" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.size = CGSizeMake(90, 40);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, -7, 0, 0);
        if ([viewController isKindOfClass:[MCPickNumberViewController class]]) {
            [button addTarget:self action:@selector(popBackToViewController) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [button addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
        }
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        viewController.hidesBottomBarWhenPushed = YES;
    }

    [super pushViewController:viewController animated:animated];
}

- (void)personInfoBtnClick:(UIButton *)btn{

    _isOpen=!_isOpen;
    if (_isOpen) {
        self.coverView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            CGFloat K=1.0*(G_SCREENWIDTH-40.0)/G_SCREENWIDTH;
            _screenImgV.frame=CGRectMake(20, 305, G_SCREENWIDTH-40, G_SCREENHEIGHT*K);
            self.screenImgV.image=[self getSnapshotImage];
            [self.selectedView reloadData];
            [self.selectedView refreashImgVIcon];
        } completion:^(BOOL finished) {
            self.tabBarController.tabBar.hidden = YES;
        }];
       
    } else {
        
        self.tabBarController.tabBar.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            _screenImgV.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT);
        } completion:^(BOOL finished) {
            self.coverView.hidden = YES;
        }];
    }
}
- (void)coverViewClick{
    _isOpen=NO;
    self.tabBarController.tabBar.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _screenImgV.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT);
    } completion:^(BOOL finished) {
        self.coverView.hidden = YES;
    }];
}
- (void)popBackToViewController{
    
    MCPaySLBaseModel * model=[MCPaySLBaseModel sharedMCPaySLBaseModel];
    if (model.dataSource.count == 0) {
        [self pop2RootViewController];
    }else{
    MCPopAlertView *mcAlertView = [[MCPopAlertView alloc] initWithType:MCPopAlertTypeTZRequest_Confirm Title:@"提示" message:@"返回将清空已选号码，确定返回吗？" leftBtn:@"确定" rightBtn:@"取消"];
    
    mcAlertView.resultIndex = ^(NSInteger index){
        if (index==1) {
            /*
             * 清空购彩蓝
             */
            
            [model removeDataSource];
            
            [self pop2RootViewController];
        }
    };
    [mcAlertView showXLAlertView];
    }
}
- (void)pop2RootViewController{
    
    [UIView animateWithDuration:0.01 animations:^{
    // nothing
    } completion:^(BOOL finished) {
        if (finished) {
            
            [self popToRootViewControllerAnimated:YES];
            [self popViewControllerAnimated:YES];
            return;
        }
    }];
}
-(UIImage *)captureImageFromViewLow:(UIView *)orgView {
    //获取指定View的图片
    UIGraphicsBeginImageContextWithOptions(orgView.bounds.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [orgView.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)getSnapshotImage{
    return [self captureImageFromViewLow:self.view];
}


#pragma mark-添加银行卡
-(void)delay_GoToMCMineAddBankCardViewController{
    //先绑卡-》设置资金密码-》退回我的
    MCMineAddBankCardViewController * vc=[[MCMineAddBankCardViewController alloc]init];
    vc.type=NOPasswordAndNOCard;
    self.navigationBarHidden=NO;
    [self pushViewController:vc animated:YES];
}

#pragma mark-资金密码
-(void)delay_GoToMCModifyPayPasswordViewController{
    //先验证密保问题
    [self enSureSecureQuestion];
    
    //    MCModifyPayPasswordViewController * vc =[[MCModifyPayPasswordViewController alloc]init];
    //    self.navigationBarHidden=NO;
    //    [self pushViewController:vc animated:YES];
}

#pragma mark-验证密保
-(void)enSureSecureQuestion{
    __weak __typeof__ (self) wself = self;
    
    MCGetRandomSecurityModel * getRandomSecurityModel = [MCGetRandomSecurityModel sharedMCGetRandomSecurityModel];
    //    if (getRandomSecurityModel.dataSource.Question.length>0) {
    //        [wself popRandomSecurity:getRandomSecurityModel.dataSource];
    //    }else{
    _getRandomSecurityModel=getRandomSecurityModel;
    [BKIndicationView showInView:self.view];
    [getRandomSecurityModel refreashDataAndShow];
    getRandomSecurityModel.callBackSuccessBlock = ^(id manager) {
        NSArray * arr =manager;
        if (arr.count>0) {
            wself.getRandomSecurityModel.dataSource = [MCSecurityQuestionModel mj_objectWithKeyValues:manager[0]];
            [wself popRandomSecurity:wself.getRandomSecurityModel.dataSource];
        }
        
    };
    
    getRandomSecurityModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
    };
    //    }
}

-(void)popRandomSecurity:(MCSecurityQuestionModel *)model{
    __weak __typeof__ (self) wself = self;
    
    NSString * question = [NSString stringWithFormat:@"\n%@",model.Question];
    //创建UIAlertController 设置标题，信息，样式
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"验证密保问题" message:question preferredStyle:UIAlertControllerStyleAlert];
    
    //添加UITextField
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入答案！";
        textField.keyboardType = UIKeyboardTypeDefault;
        [textField addTarget:wself action:@selector(textFieldChane:) forControlEvents:UIControlEventEditingChanged];
        _textField=textField;
    }];
    
    //创建UIAlertAction对象，设置标题并添加到UIAlertController上
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:cancelAction];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self retrievePasswordModel:model];
        
    }];
    sureAction.enabled=NO;
    _sureAction=sureAction;
    //设置UIAlertAction对象是否可用
    [alertController addAction:sureAction];
    
    //展现UIAlertController
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark-验证密保答案是否正确
-(void)retrievePasswordModel:(MCSecurityQuestionModel *)model{
    
    __weak __typeof__ (self) wself = self;
    MCMineInfoModel * mineInfoModel=[MCMineInfoModel sharedMCMineInfoModel];
    
    NSString * UserName;
    if (mineInfoModel.UserName.length>1) {
        UserName=mineInfoModel.UserName;
    }else{
        UserName=[[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
    }
    NSDictionary * dic = @{
                           @"UserName":UserName,//    是    String    用户名称
                           @"RecoveryMode":@"2",//    是    Int    找回方式（1：按资金密码 2：通过密保答案找回），此处传固定值2
                           @"SecurityID":model.ID,//    是    Int    当前问题的ID值
                           @"Answer":_textField.text//    是    String    用户输入答案
                           };
    MCRetrievePasswordModel * retrievePasswordModel = [[MCRetrievePasswordModel alloc]initWithDic:dic];
    _retrievePasswordModel = retrievePasswordModel;
    [BKIndicationView showInView:self.view];
    [retrievePasswordModel refreashDataAndShow];
    retrievePasswordModel.callBackSuccessBlock = ^(id manager) {
        
        MCModifyPayPasswordViewController * vc =[[MCModifyPayPasswordViewController alloc]init];
        wself.navigationBarHidden=NO;
        [wself pushViewController:vc animated:YES];
        
    };
    
    retrievePasswordModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
    };
    
    
    
}

-(void)textFieldChane:(UITextField *)tf{
    if (tf.text.length>0) {
        _sureAction.enabled=YES;
    }else{
        _sureAction.enabled=NO;
    }
}

#pragma mark-密保设置
-(void)delay_GoToMCMSecureSettingViewController{
    MCMSecureSettingViewController *svc=[[MCMSecureSettingViewController alloc]init];
    svc.Type = MCMSecureSettingType_FirstSet;
    self.navigationBarHidden=NO;
    [self pushViewController:svc animated:YES];
}


@end
